/**
 * Created by 瑱彬 on 2015/4/8.
 */



var windowInofOpts = {
    width: 250,     // 信息窗口宽度
//    height: 250,		 // 信息窗口高度
    title: "车辆详情"
};

function openFrontWIInfo(car) {
    var point = new BMap.Point(car.gpsooCar.lng, car.gpsooCar.lat);
    var infoWindow = new BMap.InfoWindow("加载中...", windowInofOpts);  // 创建信息窗口对象
    map.openInfoWindow(infoWindow, point); //开启信息窗口
    getCarFrontContent(car, infoWindow);
}
function addShowFrontWIClickHandler(car) {
    car.marker.addEventListener("click", function (e) {
        openFrontWIInfo(car)
    });
}

function getCarFrontContent(car, infoWindow) {
    var content = "<table class='carFrontWindowInfoTable'><tr><td width='80px'>车牌号:</td><td>" + car.carNum + "</td></tr>"
        + "<tr><td>型号:</td><td>" + car.carModel + "</td></tr>"
        + "<tr><td>部门:</td><td>" + car.sectorName + "</td></tr>"
        + "<tr><td>IMEI:</td><td>" + car.carImei + "</td></tr>"
        + "<tr><td>时速:</td><td>" + (car.gpsooCar.speed == -1 ? "熄火" : car.gpsooCar.speed) + "</td></tr>"
        + "<tr><td>状态:</td><td>" + deviceInfoStr[car.gpsooCar.deviceInfo] + "</td></tr>"
        + "<tr><td>地址:</td><td>address</td></tr>"
        + "</table>" +
        "<span><a href='" + CONTEXT + "/follow?id=" + car.carId + "'>查看详情</a></span>";
    var carInfoWindowContent;
    gpsoo.loadAddress(car.gpsooCar.lng, car.gpsooCar.lat, function (data) {
        car.address = data.address;
        carInfoWindowContent = content.replace(/address/g, car.address);
        infoWindow.setContent(carInfoWindowContent);
    })
}

var initCar = function () {
    $.get(CONTEXT + '/ajax/car/frontData', function (data) {
        cars = data.rows;
        var imeis = "";
        for (i = 0; i < cars.length; i++) {
            imeis += cars[i].carImei + ",";
        }
        imeis = imeis.substr(0, imeis.length - 1);

        paintCarInMap(imeis, addShowFrontWIClickHandler);

        setInterval("paintCarInMap(" + imeis + ",addShowFrontWIClickHandler)", 5000);
        afterInitCar();
    });
};

var isAccordWithCar = function (car, key) {
    if (key == null || key == "") {
        return false;
    }
    var keyPatt = new RegExp(key);
    return keyPatt.test(car.carImei) || keyPatt.test(car.carNum) || keyPatt.test(car.carModel) || keyPatt.test(car.address);
};

/**
 * 显示找不到对话框...是挺惨的呵呵
 * */

var showNotFindMsg = function () {
    var nothingFoundHtml = '<div class="alert alert-warning alert-dismissible" role="alert" id="alert_' + msgId + '">' +
        '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
        '<strong>呵呵哒</strong>没有找到符合条件的车车' +
        '</div>';
    msgId++;
    $("#alertDiv").append(nothingFoundHtml);
    $("#alert_" + (msgId - 1)).delay(1000).fadeOut('slow', function () {
        $(this).remove();
    });
};

/**
 * 通过关键字搜索
 */
var getCarByKey = function (key) {
    for (var i = 0; i < cars.length; i++) {
        var car = cars[i];
        if (isAccordWithCar(car, key)) {
            return car;
        }
    }
    showNotFindMsg();
};
/**下滑框点击确定事件HTML*/
var getBindScript = function (selector, functionName) {
    var bindStr =
        '$(".' + selector + '-message").on("click", function (event) {' +
        '    var $block = $(this).children(".carImei_' + selector + '_text");' +
        '    if ($block == undefined || $block == null) {' +
        '        showNotFindMsg();' +
        '    }' +
        '    var key = $block.html();' +
        '    ' + functionName + '(key);' +
        '});';
    return '<script>' + bindStr + '<\/script>';
};

/**
 * 跟踪动作
 */
var followCar = function (key) {
    var car = getCarByKey(key);
    window.location.href = CONTEXT + "/follow?id=" + car.carId;
};
/**
 * 搜索动作
 */
var searchCar = function (key) {
    var car = getCarByKey(key);
    if (car != undefined && car != null) {
        focusOnCar(car);
    }
};
/**
 * 搜索的BloodHoundAdapter
 */
var searchAdapter;
var followAdapter;

var getBloodhoundAdapter = function () {
    var bloodhoundAdapter = new Bloodhound({
        datumTokenizer: function (cars) {
            var carImeiBloodHound = Bloodhound.tokenizers.whitespace(cars.carImei);
            var carNumBloodHound = Bloodhound.tokenizers.whitespace(cars.carNum);
            var carModelBloodHound = Bloodhound.tokenizers.whitespace(cars.carModel);
            return carImeiBloodHound.concat(carNumBloodHound).concat(carModelBloodHound);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: cars
    });
    return bloodhoundAdapter;
};


/**
 * 初始化搜索
 */
var initSearch = function () {
    if (searchAdapter == undefined || searchAdapter == null) {
        searchAdapter = getBloodhoundAdapter();
        searchAdapter.initialize();
    }
    /**
     * 初始化 搜索typeahead
     * */
    $('#search_key').typeahead(null, {
        name: 'carImei',
        displayKey: 'carImei',
        source: searchAdapter.ttAdapter(),
        templates: {
            empty: [
                '<div class="search-message text-warning">',
                '没有找到符合条件的车车',
                '</div>'
            ].join('\n'),
            suggestion: function (data) {
                return '<p class="search-message text-success"><strong class="carImei_search_text">' + data.carImei + '</strong> - ' + data.carNum + ' - ' + data.carModel + '</p>';
            },
            footer: getBindScript("search", "searchCar")


        }
    });
    $("#car_search").on('submit', function (event) {
        event.preventDefault();
        var key = $("#search_key").val();
        searchCar(key);
    });


};

var initFollow = function () {
    if (followAdapter == undefined || searchAdapter == null) {
        followAdapter = getBloodhoundAdapter();
        followAdapter.initialize();
    }
    /**
     * 初始化 搜索typeahead
     * */
    $('#follow_key').typeahead(null, {
        name: 'carImei',
        displayKey: 'carImei',
        source: searchAdapter.ttAdapter(),
        templates: {
            empty: [
                '<div class="follow-message text-warning">',
                '没有找到符合条件的车车',
                '</div>'
            ].join('\n'),
            suggestion: function (data) {
                return '<p class="follow-message text-success"><strong class="carImei_follow_text">' + data.carImei + '</strong> - ' + data.carNum + ' - ' + data.carModel + '</p>';
            },
            footer: getBindScript("follow", "followCar")

        }
    });

};
/**
 *在载入完车辆信息后的回调方法
 */
var afterInitCar = function () {
    initSearch();
    initFollow();
};

$(document).ready(function () {
    gpsoo.loadAccesstoken("13823862062", "123456", function () {
        initPage(17);
        initCar();
    });
});

